package com.example.drawview;

import java.util.ArrayList;

import yuku.ambilwarna.AmbilWarnaDialog;
import yuku.ambilwarna.AmbilWarnaDialog.OnAmbilWarnaListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */
	static final int REQUEST_CODE = 1001;
	ImageView img_logo;
	protected static final int CAMERA_REQUEST = 0;
	protected static final int GALLERY_PICTURE = 1;
	private Intent pictureActionIntent = null;
	Bitmap bitmap;
	public int color,backgroundColor;
	public int strokeWidth=6;
	private Paint mPaint;
	private Paint mPaintEffect;
	int num;
	LinearLayout linearLayout2;
	private ArrayList<Shape> undonePaths = new ArrayList<Shape>();
	//private ArrayList<Path> paths = new ArrayList<Path>();
	private ArrayList<Shape> shape = new ArrayList<Shape>();
	Intent intent ;
	
	public static DrawingPanel dp;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		intent = new Intent(MainActivity.this,UploadImageActivity.class);
		color = 0;
		backgroundColor=0;
//		colorpicker();
		
		linearLayout2 = (LinearLayout) findViewById(R.id.linearLayout2);
		dp= new DrawingPanel(this);
		
		linearLayout2.addView(dp);
		
		
		((Button) findViewById(R.id.button1))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (shape.size() > 0) {
							undonePaths.add(shape.remove(shape.size()-1));
							dp.invalidate();
						}
					}
				});
		((Button) findViewById(R.id.button2))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (undonePaths.size() > 0) {
							shape.add(undonePaths.remove(undonePaths.size()-1));
							dp.invalidate();
						}
					}
				});
		((Button) findViewById(R.id.button3))
		.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				undonePaths.clear();
				shape.clear();
//				dp.invalidate();
			}
		});	
		((Button) findViewById(R.id.button4))
		.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				LaunchColorPicker();
				colorpicker();
			}
		});	
		((Button) findViewById(R.id.button5))
		.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				LaunchColorPicker();
				seekbar();
			}
		});	
		((Button) findViewById(R.id.button6))
		.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				LaunchColorPicker();
				background();
			}
		});	
	}

public class DrawingPanel extends View implements OnTouchListener {
		Shape currentShape;
		private Canvas mCanvas;
		//private Path mPath;
		private float xleft, xright, xtop, xbottom;
		public ArrayList<Shape> getShape(){
        	return shape;
        }
		public DrawingPanel(Context context) {
			super(context);
			setFocusable(true);
			setFocusableInTouchMode(true);
			this.setOnTouchListener(this);
			
			mPaint = new Paint();
			mPaint.setAntiAlias(true);
			mPaint.setColor(0);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(6);
			
			mPaintEffect = new Paint();
			mPaintEffect.setAntiAlias(true);
			mPaintEffect.setStyle(Paint.Style.STROKE);
			mPaintEffect.setStrokeJoin(Paint.Join.ROUND);
			mPaintEffect.setStrokeCap(Paint.Cap.ROUND);
			
			currentShape = new Shape();
		}

		public void colorChanged(int _color_) {
			mPaint.setColor(_color_);
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			for(int i = 0; i<shape.size(); i++){
    		Shape currentGraphicObject = shape.get(i);
			mPaintEffect.setColor(Color.BLACK);
			mPaintEffect.setStrokeWidth(currentGraphicObject.getStrokeWidth()+4);
			mPaintEffect.setAlpha(50);
		//}
		
			for (Path path : currentGraphicObject.getGraphicsPath()) {
				invalidate();
				canvas.drawPath(path, mPaintEffect);
        	    //bitmapCanvas.drawPath(path,mPaint);
        	    currentGraphicObject = null;
    		
        	}
			}
				for(int i = 0; i<shape.size(); i++){
        		
        		Shape currentGraphicObject = shape.get(i);
        			mPaint.setColor(currentGraphicObject._getColor());
        			mPaint.setStrokeWidth(currentGraphicObject.getStrokeWidth());
        		//}
        		
        			for (Path path : currentGraphicObject.getGraphicsPath()) {
        				invalidate();
        				canvas.drawPath(path, mPaint);
                	    //bitmapCanvas.drawPath(path,mPaint);
                	    currentGraphicObject = null;
            		}
        	}
		}
		private float mX, mY;
		private static final float TOUCH_TOLERANCE = 0;
//
//		private void touch_start(float x, float y) {
//			mPath.reset();
//			mPath.moveTo(x, y);
//			mX = x;
//			mY = y;
//		}
//
//		private void touch_move(float x, float y) {
//			float dx = Math.abs(x - mX);
//			float dy = Math.abs(y - mY);
//			if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
//				mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
//				mX = x;
//				mY = y;
//			}
//		}
//
//		private void touch_up() {
//			mPath.lineTo(mX, mY);
//			mCanvas.drawPath(mPath, mPaint);
//			mPath = new Path();
//			paths.add(mPath);
//			
//		}

		@Override
		public boolean onTouch(View arg0, MotionEvent event) {
			float x = event.getX();
			float y = event.getY();
			switch (event.getAction()) {
			
			case MotionEvent.ACTION_DOWN:
				invalidate();
				//touch_start(x, y);
//				currentShape.getPath().reset();
				currentShape.getPath().moveTo(x, y);
				mX = x;
				mY = y;
				break;
			case MotionEvent.ACTION_MOVE:
				invalidate();
//				touch_move(x, y);
				float dx = Math.abs(x - mX);
				float dy = Math.abs(y - mY);
				if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
					currentShape.getPath().quadTo(mX, mY, (x + mX)/2,(y + mY)/2);
					mX = x;
					mY = y;
				}
				break;
			case MotionEvent.ACTION_UP:
				invalidate();
				
				currentShape = new Shape();
				//touch_up();
//				currentShape.getPath().lineTo(mX, mY);
//				mCanvas.drawPath(currentShape.getPath(), mPaint);
//				currentShape.getPath().lineTo(x, y);
				currentShape.getGraphicsPath().add(currentShape.getPath());
				currentShape._setColor(color);
				currentShape.setStrokeWidth(strokeWidth);
				shape.add(currentShape);
				num++;
				break;
			}
			return true;
			
		}
	}
	
	public void colorpicker() {
        	AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, 0xff0000ff, new OnAmbilWarnaListener() {
            @Override
            public void onCancel(AmbilWarnaDialog dialog){
            }
            @Override
            public void onOk(AmbilWarnaDialog dialog, int color_) {
                MainActivity.this.color = color_;
            }
        });
        dialog.show();
    }
	public void backgroundColorpicker() {
    	AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, 0xff0000ff, new OnAmbilWarnaListener() {
        @Override
        public void onCancel(AmbilWarnaDialog dialog){
        }
        @Override
        public void onOk(AmbilWarnaDialog dialog, int color_) {
            backgroundColor = color_;
            dp.setBackgroundColor(backgroundColor);
    		dp.invalidate();
        }
    });
    dialog.show();
}
	public void seekbar() 
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.dialog, (ViewGroup)findViewById(R.id.your_dialog_root_element));
		final SeekBar yourDialogSeekBar = (SeekBar)layout.findViewById(R.id.your_dialog_seekbar);
		yourDialogSeekBar.setProgress(strokeWidth);
		OnSeekBarChangeListener yourSeekBarListener = new OnSeekBarChangeListener() {
		    @Override
		    public void onStopTrackingTouch(SeekBar seekBar) {
		            //add code here
		    }

		    @Override
		    public void onStartTrackingTouch(SeekBar seekBar) {
		            //add code here
		    }

		    @Override
		    public void onProgressChanged(SeekBar seekBark, int progress, boolean fromUser) {
		            //add code here
		    }
		 };
		 
		yourDialogSeekBar.setOnSeekBarChangeListener(yourSeekBarListener);
		
		builder.setView(layout)
			   .setCancelable(false)
		       .setPositiveButton("Select", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int id) {
		            
		        	int value = yourDialogSeekBar.getProgress();
		       		Log.e("-------1",""+value);
		       		MainActivity.this.strokeWidth=value;
		       		dialog.dismiss();
		       }
		   })
		       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		       public void onClick(DialogInterface dialog, int id) {
		            dialog.cancel();
		       }
		   });
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	public void background() 
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
//		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
//		Menu layout = (Menu) inflater.inflate(R.menu.main, (ViewGroup)findViewById(R.id.your_dialog_root_element)); 
//		
		builder.setTitle("Select")
			   .setCancelable(false)
		       .setPositiveButton("Photo", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int id) {
		            	photoDialog();
		       }
		   })
		       .setNeutralButton("Color", new DialogInterface.OnClickListener() {
		       public void onClick(DialogInterface dialog, int id) {
		            backgroundColorpicker();
		       }
		   }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	public void photoDialog() {
		 AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
		    myAlertDialog.setTitle("Upload Pictures Option");
		    myAlertDialog.setMessage("How do you want to set your picture?");

		    myAlertDialog.setPositiveButton("Gallery",
		            new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface arg0, int arg1) {
		                    intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		                    intent.setType("image/*");
		                    intent.putExtra("return-data", true);
		                    startActivityForResult(intent,
		                            GALLERY_PICTURE);
		                }
		            });

		    myAlertDialog.setNegativeButton("Camera",
		            new DialogInterface.OnClickListener() {
		                public void onClick(DialogInterface arg0, int arg1) {
		                	intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		                    startActivityForResult(intent,CAMERA_REQUEST);

		                }
		            });
		    myAlertDialog.show();
}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	    super.onActivityResult(requestCode, resultCode, data);
	    if (requestCode == GALLERY_PICTURE) {
	        if (resultCode == RESULT_OK) {
	            if (data != null) {
	                BitmapDrawable bmpDrawable = null;
	                Cursor cursor = getContentResolver().query(data.getData(),
	                        null, null, null, null);
	                if (cursor != null) {

	                    cursor.moveToFirst();

	                    int idx = cursor.getColumnIndex(ImageColumns.DATA);
	                    String fileSrc = cursor.getString(idx);
	                    bitmap = BitmapFactory.decodeFile(fileSrc); // load
	                                                                        // preview
	                    BitmapDrawable background = new BitmapDrawable(bitmap);
	                    MainActivity.dp.setBackgroundDrawable(background);
//	                    img_logo.setImageBitmap(bitmap);
//	                    finish();
	                } 
	            } 
	        } 
	    } else if (requestCode == CAMERA_REQUEST) {
	        if (resultCode == RESULT_OK) {
	            if (data.hasExtra("data")) {

	                bitmap = (Bitmap) data.getExtras().get("data");
//	                bitmap = BitmapFactory.decodeFile(pathName);
	                BitmapDrawable background = new BitmapDrawable(bitmap);
	                MainActivity.dp.setBackgroundDrawable(background);
//	                img_logo.setImageBitmap(bitmap);
//	                finish();
	                
	            } else if (data.getExtras() == null) {

	                Toast.makeText(getApplicationContext(),
	                        "No extras to retrieve!", Toast.LENGTH_SHORT)
	                        .show();

	                BitmapDrawable thumbnail = new BitmapDrawable(
	                        getResources(), data.getData().getPath());
	            }

	        } 
	    }

	}
}